//
//  SAReturnGoodsListVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/20.
//

#import "SAReturnGoodsListVC.h"
#import "SASalesInvoiceListAPI.h"
#import "SAReturnDocumentsCell.h"
#import "SAInvoiceListModel.h"
#import "SASearchVipUserView.h"
#import "SAVipModel.h"
#import "SAReturnGoodsListDetailVC.h"

@interface SAReturnGoodsListVC ()<UITextFieldDelegate,UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITextField *searchTf;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) SASalesInvoiceListAPI *salesInvoiceListAPI;
@property (nonatomic, strong) NSMutableArray<SAInvoiceListModel *> *dataMarr;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) UIButton *vipBtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) SAVipModel *vipModel;

@end

@implementation SAReturnGoodsListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.salesInvoiceListAPI == api) {
        if (self.currentPage == 1) {
            [self.dataMarr removeAllObjects];
        }
        NSMutableArray<SAInvoiceListModel *> *marr = [SAInvoiceListModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        for (SAInvoiceListModel *model in marr) {
            [self.dataMarr addObject:model];
        }
        self.tipView.hidden = self.dataMarr.count > 0;
        [self.tableView reloadData];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAReturnDocumentsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAReturnDocumentsCell"];
    cell.returnModel = self.dataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SAInvoiceListModel *model = self.dataMarr[indexPath.section];
    SAReturnGoodsListDetailVC *pushVC = [[SAReturnGoodsListDetailVC alloc] initWithSaleOrderId:model.salesOrderId AndSaleOrderNo:model.salesOrderNo];
    WeakSelf
    pushVC.selectBlock = ^(NSMutableArray * _Nonnull marr, SASalesInvoiceDetailModel * _Nonnull model) {
        !weakSelf.goodsBlock ?: weakSelf.goodsBlock(marr,model);
    };
    [self.navigationController pushViewController:pushVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(71);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

#pragma mark - UITextField
- (void)textFieldEditChanged:(UITextField *)textField {
    self.salesInvoiceListAPI.salesOrderNo = textField.text;
    self.currentPage = 1;
    [self loadData];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - event
-(void)loadData {
    self.salesInvoiceListAPI.currentPage = self.currentPage;
    [self.salesInvoiceListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(void)clickedVipBtn {
    SASearchVipUserView *searchVipUserView = [SASearchVipUserView shareCornView];
    UIViewController *vc = nil;
    [searchVipUserView showView:vc];
    WeakSelf
    searchVipUserView.selectBlock = ^(SAVipModel * _Nonnull vipModel) {
        weakSelf.vipModel = vipModel;
        [weakSelf.vipBtn setTitle:[NSString stringWithFormat:@"%@(%@)",vipModel.memberName,vipModel.mobile] forState:UIControlStateNormal];
        [weakSelf.vipBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [weakSelf.vipBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
        CGFloat imageWidth = weakSelf.vipBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.vipBtn.titleLabel.bounds.size.width;
        weakSelf.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        weakSelf.cancelBtn.hidden = NO;
        weakSelf.salesInvoiceListAPI.memberId = vipModel.memberId;
        weakSelf.salesInvoiceListAPI.currentPage = 1;
        [weakSelf loadData];
    };
}

-(void)clickedCancelBtn {
    self.cancelBtn.hidden = YES;
    self.vipModel = nil;
    [self.tableView reloadData];
    [self.vipBtn setTitle:@"请选择会员" forState:UIControlStateNormal];
    [self.vipBtn setTitleColor:kLightgGrayColor forState:UIControlStateNormal];
    CGFloat imageWidth = self.vipBtn.imageView.bounds.size.width;
    CGFloat labelWidth = self.vipBtn.titleLabel.bounds.size.width;
    self.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
    
    self.salesInvoiceListAPI.memberId = @"";
    self.salesInvoiceListAPI.currentPage = 1;
    [self loadData];
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"供货商"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    
    [self addRightViews:@[self.topView]];
    [self.topView addSubview:self.searchTf];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 40)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    NSArray *nameArr = @[@"  会员"];
    NSArray *imageArr = @[@"Sale_vip"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [titleBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        titleBtn.frame = SARectMake(20, StatusHeight, 120, 40);
        titleBtn.titleLabel.font = kFont(15);
        [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.view addSubview:titleBtn];
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
        rightBtn.frame = SARectMake(0, StatusHeight, kBaseScreenWidth - 20, 40);
        rightBtn.titleLabel.font = kFont(15);
        rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [rightBtn setTitle:@"请选择会员" forState:UIControlStateNormal];
        [rightBtn setTitleColor:kLightgGrayColor forState:UIControlStateNormal];
        [self.view addSubview:rightBtn];
        
        CGFloat imageWidth = rightBtn.imageView.bounds.size.width;
        CGFloat labelWidth = rightBtn.titleLabel.bounds.size.width;
        rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        
        [rightBtn addTarget:self action:@selector(clickedVipBtn) forControlEvents:UIControlEventTouchUpInside];
        self.vipBtn = rightBtn;
    }
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancle"] forState:UIControlStateNormal];
    cancelBtn.frame = SARectMake(kBaseScreenWidth - 37, StatusHeight, 30, 40);
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn addTarget:self action:@selector(clickedCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [self.view addSubview:cancelBtn];
    
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.tipView];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
    
    self.currentPage = 1;
    self.salesInvoiceListAPI.pageSize = 20;
    [self loadData];
}

#pragma mark - lazy
-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:SARectMake(63, 0, 312, 44)];
    }
    return _topView;
}

-(UITextField *)searchTf {
    if (!_searchTf) {
        _searchTf = [[UITextField alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
        _searchTf.placeholder = @"请输入单号";
        _searchTf.backgroundColor = [UIColor whiteColor];
        _searchTf.layer.cornerRadius = kScaleNum(5);
        _searchTf.layer.masksToBounds = YES;
        _searchTf.delegate = self;
        _searchTf.font = kFont(14);
        _searchTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIView *leftView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 26, 30)];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(6, 7, 14, 16)];
        imageV.image = [UIImage imageNamed:@"shop_search"];
        [leftView addSubview:imageV];
        _searchTf.leftView = leftView;
        _searchTf.leftViewMode = UITextFieldViewModeAlways;
        _searchTf.returnKeyType = UIReturnKeyDone;
        [_searchTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTf;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 47), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 47)) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SAReturnDocumentsCell class] forCellReuseIdentifier:@"SAReturnDocumentsCell"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
    }
    return _tableView;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 47), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 47))];
        _tipView.backgroundColor = kLineColor;
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 150, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

-(SASalesInvoiceListAPI *)salesInvoiceListAPI {
    if (!_salesInvoiceListAPI) {
        _salesInvoiceListAPI = [SASalesInvoiceListAPI apiWithDelegate:self];
    }
    return _salesInvoiceListAPI;
}

-(NSMutableArray<SAInvoiceListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

@end
